"""
剪映草稿项目管理CLI命令
"""

import asyncio
import click
from pathlib import Path
from typing import Optional

from src.core.di import injector
from src.services.jianying_draft_service import JianyingDraftService
from src.services.jianying_template_analyzer import JianyingTemplateAnalyzer
from src.services.jianying_template_scanner import JianyingTemplateScanner


def run_async(coro):
    """运行异步函数的辅助函数"""
    import asyncio
    try:
        # 尝试获取当前事件循环
        asyncio.get_running_loop()
        # 如果已经在事件循环中，使用线程池
        import concurrent.futures

        # 在新线程中运行异步函数
        def run_in_thread():
            new_loop = asyncio.new_event_loop()
            asyncio.set_event_loop(new_loop)
            try:
                return new_loop.run_until_complete(coro)
            finally:
                new_loop.close()

        with concurrent.futures.ThreadPoolExecutor() as executor:
            future = executor.submit(run_in_thread)
            return future.result()

    except RuntimeError:
        # 没有运行的事件循环，直接运行
        return asyncio.run(coro)





@click.group()
def jianying():
    """剪映草稿项目管理工具"""
    pass


@jianying.command()
@click.argument('templates_dir', type=click.Path(exists=True, file_okay=False, dir_okay=True))
@click.option('--output', '-o', type=click.Path(), help='输出结果到文件')
@click.option('--format', '-f', type=click.Choice(['table', 'json']), default='table', help='输出格式')
def scan(templates_dir: str, output: Optional[str], format: str):
    """
    扫描剪映草稿项目模板
    
    TEMPLATES_DIR: 模板目录路径
    """
    # 使用异步辅助函数
    service = injector.get(JianyingDraftService)
    templates = run_async(service.scan_template_projects(templates_dir))

    if format == 'json':
        import json
        result = json.dumps(templates, ensure_ascii=False, indent=2)
        if output:
            with open(output, 'w', encoding='utf-8') as f:
                f.write(result)
            click.echo(f"✅ 结果已保存到: {output}")
        else:
            click.echo(result)
    else:
        # 表格格式输出
        if not templates:
            click.echo("❌ 未找到任何模板项目")
            return

        click.echo(f"\n📊 找到 {len(templates)} 个模板项目:")
        click.echo("-" * 120)
        click.echo(f"{'模板ID':<20} {'模板名称':<20} {'时长':<8} {'画布':<12} {'轨道':<8} {'素材':<8} {'特效':<8} {'描述':<30}")
        click.echo("-" * 120)

        for template in templates:
            duration = template.get('duration_seconds', 0)
            canvas_info = template.get('canvas_info', {})
            canvas_str = canvas_info.get('ratio', 'N/A')
            tracks_info = template.get('tracks_info', {})
            tracks_str = f"{tracks_info.get('total', 0)}"
            effects_info = template.get('effects_info', {})
            effects_total = effects_info.get('video_effects', 0) + effects_info.get('transitions', 0)

            description = template.get('template_description', '')
            if len(description) > 28:
                description = description[:25] + '...'

            click.echo(f"{template['template_id']:<20} {template['template_name']:<20} {duration:<8.1f} {canvas_str:<12} {tracks_str:<8} {template['materials_count']:<8} {effects_total:<8} {description:<30}")

        if output:
            import json
            with open(output, 'w', encoding='utf-8') as f:
                json.dump(templates, f, ensure_ascii=False, indent=2)
            click.echo(f"\n✅ 详细结果已保存到: {output}")


@jianying.command()
@click.argument('templates_dir', type=click.Path(exists=True, file_okay=False, dir_okay=True))
@click.argument('template_id')
@click.argument('target_dir', type=click.Path())
@click.option('--name', '-n', help='新项目名称')
@click.option('--materials', '-m', multiple=True, help='自定义素材路径（可多次指定）')
def create(templates_dir: str, template_id: str, target_dir: str, name: Optional[str], materials: tuple):
    """
    基于模板创建新的草稿项目

    TEMPLATES_DIR: 模板目录路径
    TEMPLATE_ID: 模板ID
    TARGET_DIR: 目标目录路径
    """
    service = injector.get(JianyingDraftService)

    # 获取模板信息
    template_info = run_async(service.get_template_info(template_id, templates_dir))
    if not template_info:
        click.echo(f"❌ 模板不存在: {template_id}")
        return

    # 转换素材路径
    custom_materials = list(materials) if materials else None

    # 创建项目
    result = run_async(service.create_draft_from_template(
        template_info=template_info,
        target_dir=target_dir,
        project_name=name,
        custom_materials=custom_materials
    ))

    if result["success"]:
        click.echo(f"✅ 成功创建草稿项目:")
        click.echo(f"   项目ID: {result['project_id']}")
        click.echo(f"   项目名称: {result['project_name']}")
        click.echo(f"   项目路径: {result['project_path']}")
        click.echo(f"   基于模板: {result['template_id']}")
        click.echo(f"   创建文件: {', '.join(result['files_created'])}")

        if custom_materials:
            click.echo(f"   使用素材: {len(custom_materials)} 个")
    else:
        click.echo(f"❌ 创建失败: {result.get('error', '未知错误')}")


@jianying.command()
@click.argument('templates_dir', type=click.Path(exists=True, file_okay=False, dir_okay=True))
@click.argument('template_id')
def info(templates_dir: str, template_id: str):
    """
    查看模板详细信息

    TEMPLATES_DIR: 模板目录路径
    TEMPLATE_ID: 模板ID
    """
    service = injector.get(JianyingDraftService)
    template_info = run_async(service.get_template_info(template_id, templates_dir))

    if not template_info:
        click.echo(f"❌ 模板不存在: {template_id}")
        return

    click.echo(f"\n📋 模板详细信息:")
    click.echo(f"   模板ID: {template_info['template_id']}")
    click.echo(f"   模板名称: {template_info['template_name']}")
    click.echo(f"   模板路径: {template_info['template_path']}")
    click.echo(f"   描述: {template_info['template_description']}")

    # 时间信息
    if template_info['creation_time']:
        from datetime import datetime
        try:
            # 现在时间戳已经在服务中转换为秒级
            timestamp = template_info['creation_time']
            if timestamp > 0:
                create_time = datetime.fromtimestamp(timestamp)
                click.echo(f"   创建时间: {create_time.strftime('%Y-%m-%d %H:%M:%S')}")
        except (ValueError, OSError):
            # 时间戳格式无效，显示原始值
            click.echo(f"   创建时间: {template_info['creation_time']} (原始时间戳)")

    # 项目统计
    duration = template_info.get('duration_seconds', 0)
    click.echo(f"   项目时长: {duration:.1f} 秒")
    click.echo(f"   FPS: {template_info.get('fps', 'N/A')}")
    click.echo(f"   项目ID: {template_info.get('project_id', 'N/A')}")

    # 画布配置
    canvas_info = template_info.get('canvas_info', {})
    if canvas_info:
        click.echo(f"   画布配置:")
        click.echo(f"     尺寸: {canvas_info.get('width', 'N/A')}x{canvas_info.get('height', 'N/A')}")
        click.echo(f"     比例: {canvas_info.get('ratio', 'N/A')} ({canvas_info.get('aspect_ratio', 'N/A')})")

    # 轨道信息
    tracks_info = template_info.get('tracks_info', {})
    if tracks_info:
        click.echo(f"   轨道信息:")
        click.echo(f"     总数: {tracks_info.get('total', 0)}")
        click.echo(f"     视频轨道: {tracks_info.get('video_tracks', 0)}")
        click.echo(f"     音频轨道: {tracks_info.get('audio_tracks', 0)}")

        # 显示轨道详情
        track_details = tracks_info.get('details', [])
        if track_details:
            click.echo(f"     轨道详情:")
            for track in track_details[:3]:  # 只显示前3个轨道
                click.echo(f"       轨道{track['index']}: {track['type']} ({track['segments_count']}片段, {track['total_duration']:.1f}秒)")

    # 素材信息
    materials_info = template_info.get('materials_info', {})
    if materials_info:
        click.echo(f"   素材信息:")
        videos = materials_info.get('videos', {})
        audios = materials_info.get('audios', {})
        click.echo(f"     视频: {videos.get('count', 0)} 个")
        click.echo(f"     音频: {audios.get('count', 0)} 个")
        click.echo(f"     文本: {materials_info.get('texts', {}).get('count', 0)} 个")
        click.echo(f"     图片: {materials_info.get('images', {}).get('count', 0)} 个")
        click.echo(f"     贴纸: {materials_info.get('stickers', {}).get('count', 0)} 个")

    # 特效信息
    effects_info = template_info.get('effects_info', {})
    if effects_info:
        click.echo(f"   特效信息:")
        click.echo(f"     视频特效: {effects_info.get('video_effects', 0)} 个")
        click.echo(f"     转场: {effects_info.get('transitions', 0)} 个")
        click.echo(f"     动画: {effects_info.get('animations', 0)} 个")
        click.echo(f"     滤镜: {effects_info.get('filters', 0)} 个")
        click.echo(f"     贴纸: {effects_info.get('stickers', 0)} 个")

    # 导入素材信息
    imported_info = template_info.get('imported_materials_info', {})
    if imported_info:
        click.echo(f"   导入素材:")
        for material_type, info in imported_info.items():
            if info.get('count', 0) > 0:
                click.echo(f"     {material_type}: {info['count']} 个")

    click.echo(f"   解析时间: {template_info['parsed_at']}")


@jianying.command()
@click.argument('templates_dir', type=click.Path(exists=True, file_okay=False, dir_okay=True))
def list(templates_dir: str):
    """
    列出所有模板的摘要信息

    TEMPLATES_DIR: 模板目录路径
    """
    service = injector.get(JianyingDraftService)
    summaries = run_async(service.list_template_summaries(templates_dir))

    if not summaries:
        click.echo("❌ 未找到任何模板项目")
        return

    click.echo(f"\n📋 模板列表 (共 {len(summaries)} 个):")
    click.echo("=" * 80)

    for i, summary in enumerate(summaries, 1):
        duration = summary.get('duration', 0) / 1000000  # 转换为秒
        click.echo(f"{i:2d}. {summary['template_name']}")
        click.echo(f"    ID: {summary['template_id']}")
        click.echo(f"    描述: {summary['description']}")
        click.echo(f"    时长: {duration:.1f}秒 | 轨道: {summary['tracks_count']} | 素材: {summary['materials_count']}")

        if summary['creation_time']:
            from datetime import datetime
            try:
                # 现在时间戳已经在服务中转换为秒级
                timestamp = summary['creation_time']
                if timestamp > 0:
                    create_time = datetime.fromtimestamp(timestamp)
                    click.echo(f"    创建: {create_time.strftime('%Y-%m-%d %H:%M:%S')}")
            except (ValueError, OSError):
                # 时间戳格式无效，跳过显示
                pass

        if i < len(summaries):
            click.echo()


@jianying.command()
@click.argument('templates_dir', type=click.Path(exists=True, file_okay=False, dir_okay=True))
@click.argument('target_dir', type=click.Path())
@click.option('--materials-dir', '-m', type=click.Path(exists=True, file_okay=False, dir_okay=True), help='素材目录')
@click.option('--name-prefix', '-p', default='auto_project', help='项目名称前缀')
@click.option('--limit', '-l', type=int, help='限制创建数量')
def batch_create(templates_dir: str, target_dir: str, materials_dir: Optional[str], name_prefix: str, limit: Optional[int]):
    """
    批量创建草稿项目

    TEMPLATES_DIR: 模板目录路径
    TARGET_DIR: 目标目录路径
    """
    service = injector.get(JianyingDraftService)

    # 获取所有模板
    templates = run_async(service.scan_template_projects(templates_dir))
    if not templates:
        click.echo("❌ 未找到任何模板项目")
        return

    # 限制数量
    if limit and limit > 0:
        templates = templates[:limit]

    # 获取素材文件
    materials = []
    if materials_dir:
        materials_path = Path(materials_dir)
        for ext in ['*.mp4', '*.avi', '*.mov', '*.jpg', '*.png', '*.mp3', '*.wav']:
            materials.extend(materials_path.glob(ext))
        materials = [str(m) for m in materials]

    click.echo(f"🚀 开始批量创建 {len(templates)} 个项目...")
    if materials:
        click.echo(f"📁 找到 {len(materials)} 个素材文件")

    success_count = 0
    for i, template in enumerate(templates, 1):
        try:
            project_name = f"{name_prefix}_{template['template_id']}_{i:03d}"

            # 为每个项目分配素材
            project_materials = materials[:template['materials_count']] if materials else None

            result = run_async(service.create_draft_from_template(
                template_info=template,
                target_dir=target_dir,
                project_name=project_name,
                custom_materials=project_materials
            ))

            if result["success"]:
                success_count += 1
                click.echo(f"✅ [{i}/{len(templates)}] {project_name}")
            else:
                click.echo(f"❌ [{i}/{len(templates)}] {project_name}: {result.get('error', '未知错误')}")

        except Exception as e:
            click.echo(f"❌ [{i}/{len(templates)}] 创建失败: {e}")

    click.echo(f"\n📊 批量创建完成: {success_count}/{len(templates)} 成功")


@jianying.command()
@click.argument('template_path', type=click.Path(exists=True, file_okay=False, dir_okay=True))
@click.option('--output', '-o', type=click.Path(), help='输出分析结果到文件')
@click.option('--format', '-f', type=click.Choice(['json', 'summary']), default='summary', help='输出格式')
def analyze(template_path: str, output: Optional[str], format: str):
    """
    深度分析剪映模板，提取设备信息和轨道素材信息

    TEMPLATE_PATH: 单个模板目录路径
    """
    analyzer = injector.get(JianyingTemplateAnalyzer)

    try:
        # 执行完整分析
        analysis_result = analyzer.analyze_template_structure(template_path)

        if format == 'json':
            # JSON格式输出
            import json
            result_json = json.dumps(analysis_result, ensure_ascii=False, indent=2)

            if output:
                with open(output, 'w', encoding='utf-8') as f:
                    f.write(result_json)
                click.echo(f"✅ 分析结果已保存到: {output}")
            else:
                click.echo(result_json)
        else:
            # 摘要格式输出
            click.echo(f"\n🔬 模板深度分析结果:")
            click.echo(f"   模板ID: {analysis_result['template_id']}")
            click.echo(f"   模板路径: {analysis_result['template_path']}")

            # 设备信息
            device_info = analysis_result.get('device_info', {})
            click.echo(f"\n📱 设备信息 ({len(device_info)} 个字段):")
            for key, value in device_info.items():
                click.echo(f"     {key}: {value}")

            # 主要视频轨道
            main_track = analysis_result.get('main_video_track')
            if main_track:
                click.echo(f"\n🎬 主要视频轨道:")
                click.echo(f"     轨道索引: {main_track['track_index']}")
                click.echo(f"     轨道ID: {main_track['track_id']}")
                click.echo(f"     视频片段数: {main_track['video_segments_count']}")
                click.echo(f"     总片段数: {main_track['total_segments_count']}")

            # 视频片段详情
            video_segments = analysis_result.get('video_segments', [])
            if video_segments:
                click.echo(f"\n📹 视频片段详情 ({len(video_segments)} 个):")
                for i, segment in enumerate(video_segments):
                    click.echo(f"     片段 {i+1}:")
                    click.echo(f"       ID: {segment.get('segment_id', 'N/A')}")
                    click.echo(f"       素材ID: {segment.get('material_id', 'N/A')}")
                    click.echo(f"       时间: {segment.get('target_start', 0):.1f}s - {segment.get('target_end', 0):.1f}s")
                    click.echo(f"       尺寸: {segment.get('material_width', 0)}x{segment.get('material_height', 0)}")
                    click.echo(f"       变换: scale=({segment.get('transform_scale_x', 1.0):.2f}, {segment.get('transform_scale_y', 1.0):.2f})")

            # 分析摘要
            summary = analysis_result.get('analysis_summary', {})
            click.echo(f"\n📊 分析摘要:")
            click.echo(f"     设备信息字段: {summary.get('device_fields_count', 0)} 个")
            click.echo(f"     找到主轨道: {'是' if summary.get('main_track_found', False) else '否'}")
            click.echo(f"     视频片段数: {summary.get('video_segments_count', 0)} 个")
            click.echo(f"     总视频时长: {summary.get('total_video_duration', 0):.1f} 秒")

            if output:
                import json
                with open(output, 'w', encoding='utf-8') as f:
                    json.dump(analysis_result, f, ensure_ascii=False, indent=2)
                click.echo(f"\n💾 完整分析结果已保存到: {output}")

    except Exception as e:
        click.echo(f"❌ 分析失败: {e}")


@jianying.command()
@click.argument('template_path', type=click.Path(exists=True, file_okay=False, dir_okay=True))
@click.option('--output', '-o', type=click.Path(), default='replacement_template.json', help='输出替换模板文件路径')
def extract_template(template_path: str, output: str):
    """
    提取用于素材替换的模板信息

    TEMPLATE_PATH: 单个模板目录路径
    """
    analyzer = injector.get(JianyingTemplateAnalyzer)

    try:
        # 执行完整分析
        analysis_result = analyzer.analyze_template_structure(template_path)

        # 生成替换模板
        replacement_template = analyzer.extract_replacement_template(analysis_result)

        # 保存替换模板
        import json
        with open(output, 'w', encoding='utf-8') as f:
            json.dump(replacement_template, f, ensure_ascii=False, indent=2)

        click.echo(f"✅ 替换模板提取成功:")
        click.echo(f"   模板ID: {replacement_template['template_info']['template_id']}")
        click.echo(f"   轨道索引: {replacement_template['track_info']['track_index']}")
        click.echo(f"   片段数量: {len(replacement_template['segments_template'])}")
        click.echo(f"   输出文件: {output}")

        # 显示设备信息
        device_info = replacement_template['template_info']['device_info']
        click.echo(f"\n📱 设备信息:")
        for key, value in device_info.items():
            click.echo(f"     {key}: {value}")

        # 显示片段摘要
        segments = replacement_template['segments_template']
        click.echo(f"\n📹 片段摘要:")
        for i, segment in enumerate(segments):
            timing = segment['timing']
            material = segment['material_properties']
            click.echo(f"     片段 {i+1}: {timing['target_start']:.1f}s-{timing['target_end']:.1f}s ({material['width']}x{material['height']})")

    except Exception as e:
        click.echo(f"❌ 提取失败: {e}")


@jianying.command()
@click.argument('templates_dir', type=click.Path(exists=True, file_okay=False, dir_okay=True))
@click.option('--force', '-f', is_flag=True, help='强制更新已存在的模板')
@click.option('--output', '-o', type=click.Path(), help='输出扫描结果到文件')
def scan_to_db(templates_dir: str, force: bool, output: Optional[str]):
    """
    扫描模板目录并保存到数据库

    TEMPLATES_DIR: 模板目录路径
    """
    scanner = injector.get(JianyingTemplateScanner)

    try:
        # 开始扫描
        click.echo(f"🚀 开始扫描模板目录: {templates_dir}")
        if force:
            click.echo("⚠️ 强制更新模式：将更新所有已存在的模板")

        scan_result = scanner.scan_templates_directory(templates_dir, force_update=force)

        # 显示结果
        click.echo(f"\n📊 扫描完成:")
        click.echo(f"   总共找到: {scan_result['total_found']} 个模板")
        click.echo(f"   成功处理: {scan_result['processed']} 个")
        click.echo(f"   新增模板: {scan_result['new_templates']} 个")
        click.echo(f"   更新模板: {scan_result['updated_templates']} 个")
        click.echo(f"   跳过模板: {scan_result['skipped_templates']} 个")
        click.echo(f"   失败模板: {scan_result['failed_templates']} 个")
        click.echo(f"   耗时: {scan_result['duration']:.1f} 秒")

        # 显示失败的模板
        failed_templates = [r for r in scan_result['template_results'] if r['action'] == 'failed']
        if failed_templates:
            click.echo(f"\n❌ 失败的模板:")
            for failed in failed_templates:
                click.echo(f"   - {failed['template_id']}: {failed.get('error', '未知错误')}")

        # 保存详细结果
        if output:
            import json
            with open(output, 'w', encoding='utf-8') as f:
                json.dump(scan_result, f, ensure_ascii=False, indent=2, default=str)
            click.echo(f"\n💾 详细扫描结果已保存到: {output}")

    except Exception as e:
        click.echo(f"❌ 扫描失败: {e}")


@jianying.command()
@click.argument('template_id')
def db_info(template_id: str):
    """
    从数据库获取模板信息

    TEMPLATE_ID: 模板ID
    """
    scanner = injector.get(JianyingTemplateScanner)

    try:
        template = scanner.get_template_by_id(template_id)

        if not template:
            click.echo(f"❌ 模板不存在: {template_id}")
            return

        click.echo(f"\n📋 模板信息 (来自数据库):")
        click.echo(f"   模板ID: {template['template_id']}")
        click.echo(f"   模板名称: {template['template_name']}")
        click.echo(f"   模板路径: {template['template_path']}")
        click.echo(f"   描述: {template['template_description']}")
        click.echo(f"   时长: {template['duration_seconds']:.1f} 秒")
        click.echo(f"   FPS: {template['fps']}")
        click.echo(f"   画布: {template['canvas_width']}x{template['canvas_height']} ({template['canvas_ratio']})")
        click.echo(f"   轨道: {template['tracks_count']} (视频:{template['video_tracks_count']}, 音频:{template['audio_tracks_count']})")
        click.echo(f"   素材: {template['materials_count']} 个")
        click.echo(f"   视频片段: {template['video_segments_count']} 个")
        click.echo(f"   特效: {template['effects_count']} 个")

        # 设备信息
        device_info = template.get('device_info', {})
        if device_info:
            click.echo(f"\n📱 设备信息:")
            for key, value in device_info.items():
                click.echo(f"     {key}: {value}")

        # 视频片段摘要
        segments = template.get('video_segments', [])
        if segments:
            click.echo(f"\n📹 视频片段 ({len(segments)} 个):")
            for segment in segments[:5]:  # 只显示前5个
                click.echo(f"     片段 {segment['segment_index']+1}: {segment['target_start']:.1f}s-{segment['target_end']:.1f}s ({segment['material_width']}x{segment['material_height']})")

            if len(segments) > 5:
                click.echo(f"     ... 还有 {len(segments)-5} 个片段")

        click.echo(f"\n🕒 数据库记录:")
        click.echo(f"   创建时间: {template.get('created_at', 'N/A')}")
        click.echo(f"   更新时间: {template.get('updated_at', 'N/A')}")

    except Exception as e:
        click.echo(f"❌ 获取模板信息失败: {e}")


@jianying.command()
@click.option('--duration-min', type=float, help='最小时长(秒)')
@click.option('--duration-max', type=float, help='最大时长(秒)')
@click.option('--canvas-ratio', help='画布比例')
@click.option('--min-segments', type=int, help='最少视频片段数')
@click.option('--max-segments', type=int, help='最多视频片段数')
@click.option('--limit', type=int, default=20, help='限制结果数量')
def db_search(duration_min: Optional[float], duration_max: Optional[float],
              canvas_ratio: Optional[str], min_segments: Optional[int],
              max_segments: Optional[int], limit: int):
    """
    在数据库中搜索模板
    """
    scanner = injector.get(JianyingTemplateScanner)

    try:
        templates = scanner.search_templates(
            duration_min=duration_min,
            duration_max=duration_max,
            canvas_ratio=canvas_ratio,
            min_segments=min_segments,
            max_segments=max_segments
        )

        if not templates:
            click.echo("❌ 未找到符合条件的模板")
            return

        # 限制结果数量
        templates = templates[:limit]

        click.echo(f"\n🔍 搜索结果 (显示前 {len(templates)} 个):")
        click.echo("-" * 120)
        click.echo(f"{'模板ID':<20} {'模板名称':<20} {'时长':<8} {'画布':<12} {'片段':<6} {'特效':<6} {'描述':<30}")
        click.echo("-" * 120)

        for template in templates:
            description = template['template_description']
            if len(description) > 28:
                description = description[:25] + '...'

            click.echo(f"{template['template_id']:<20} {template['template_name']:<20} {template['duration_seconds']:<8.1f} {template['canvas_ratio']:<12} {template['video_segments_count']:<6} {template['effects_count']:<6} {description:<30}")

        if len(templates) == limit:
            click.echo(f"\n💡 结果已限制为 {limit} 个，使用 --limit 参数查看更多")

    except Exception as e:
        click.echo(f"❌ 搜索失败: {e}")


@jianying.command()
def db_stats():
    """
    显示数据库统计信息
    """
    scanner = injector.get(JianyingTemplateScanner)

    try:
        stats = scanner.get_scan_statistics()

        click.echo(f"\n📊 数据库统计信息:")
        click.echo(f"   总模板数: {stats['total_templates']} 个")
        click.echo(f"   总视频片段: {stats['total_video_segments']} 个")

        if stats.get('latest_scan'):
            click.echo(f"   最近扫描: {stats['latest_scan']}")

        # 画布比例分布
        ratio_dist = stats.get('canvas_ratio_distribution', {})
        if ratio_dist:
            click.echo(f"\n📐 画布比例分布:")
            for ratio, count in ratio_dist.items():
                click.echo(f"     {ratio}: {count} 个")

        # 时长分布
        duration_dist = stats.get('duration_distribution', {})
        if duration_dist:
            click.echo(f"\n⏱️ 时长分布:")
            for duration_range, count in duration_dist.items():
                click.echo(f"     {duration_range}: {count} 个")

    except Exception as e:
        click.echo(f"❌ 获取统计信息失败: {e}")


if __name__ == '__main__':
    jianying()
